﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dynamicweb;
using Dynamicweb.Extensibility;
using Dynamicweb.eCommerce.Orders;
using Dynamicweb.eCommerce.Orders.SalesDiscounts;

namespace DwProjectTemplate.CustomModules.Providers
{
	[AddInName( "SalesDiscountProvider1" ), AddInDescription( "The specific discount provider" ),
	AddInActive( DwProjectTemplate.App.CodeSettings.EnableSalesDiscountProvider1 ), AddInIsAdditional( true )]
	public class SalesDiscountProvider1 : SalesDiscountProvider
	{
		public override void ProcessOrder( Order order )
		{
			if ( DwProjectTemplate.App.CodeSettings.EnableSalesDiscountProvider1 )
			{
				switch ( DiscountValue.Type )
				{
					case DiscountTypes.FixedAmount:
						//Add code here
						break;
					case DiscountTypes.Percent:
						//COMMENT: Example of a Custom Sales Discount calculation
						AddSalesDiscountByPercent( order );
						break;
					case DiscountTypes.Products:
						//Add code here
						break;
					case DiscountTypes.Unknown:
						//Add code here
						break;
				}
			}
		}

		private void AddSalesDiscountByPercent( Order order )
		{
			// Get the VAT on the country settings 
			double vatpercent = Dynamicweb.eCommerce.Common.Context.Country.Vat;

			// Convert the value to a percentage we can calculate with
			double discountpercent = ( DiscountValue.Amount / 100 );

			/* 
			 * Try to get the orderline on the users cart that holds our Sales Discount 
			 * This currently can't be done it would be nice though and it would 
			 * spare a lot of OrderLine number generations 
			 */
			//OrderLine ol = Dynamicweb.eCommerce.Common.Context.Cart.OrderLines.Cast<OrderLine>().Where( olSD => olSD.DiscountID == this.DiscountID ).SingleOrDefault();

			
			OrderLine ol = new OrderLine();
			ol.ID = Dynamicweb.eCommerce.Common.NumberGenerator.GetNumber( "OL" );
			ol.DiscountID = this.DiscountID;
			ol.Order = order;
			ol.ProductName = "Sales Discount";
			ol.Quantity = 1;
			ol.Type = Dynamicweb.Base.ChkString( Dynamicweb.Base.ChkNumber( OrderLine.OrderLineType.Discount ) );

			// Update the price
			ol.SetUnitPrice( order.PriceBeforeFees.PriceWithoutVAT * discountpercent * -1 );

			// Add the orderline to the order
			order.OrderLines.Add( ol );
		}
	}
}


